package org.lab.xmlparser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.lab.bean.ModelBean;
import org.lab.metricmodel.MyFilter;
import org.lab.service.ResourceConvert;
import org.lab.util.NullToString;

public class Xmlbuilder {
	private Logger log = Logger.getLogger(this.getClass());
	public boolean compareFile(String filename){
		boolean result =false;
		ResourceBundle resource = ResourceBundle.getBundle("xmlPath");
		String fileP = resource.getString("xmlPaths");
		File path = new File(fileP);// 鏌ヨ璺緞
		File[] strList; // 瀛樻斁鎵�鏈夋煡璇㈢粨鏋�
		int i = 0;
		//String image;
		ArrayList list = new ArrayList();
		strList = path.listFiles(new MyFilter());
		for (i = 0; i < strList.length; i++) {
			if (strList[i].isDirectory()) { // 鍒ゆ柇鏄惁鏄洰褰�
				;
			} else {
				
				String fileN = strList[i].getName();
				log.info(result);
				log.info(fileN);
				if(filename.equals(fileN)){
					result = true;
					break;
				}else{
					result = false;
				}
				
			}
		}
		return result;
	}
	
	public  String FindId(String filename) throws DocumentException{
		ResourceBundle resource = ResourceBundle.getBundle("xmlPath");
		String path = resource.getString("xmlPath");
		Parserxml pxml = new Parserxml();
		Document Doc = pxml.getDocument(path+"\\"+filename + ".xml");
		Element element = pxml.getNode(Doc,"//xpdl/Package/ModelHeader/Id");
		String id = element.getText();
		return id;
	}
	public boolean xmlCreat(String Idm, HttpServletRequest req,String modelname) throws IOException{
		boolean result = false;
		ResourceBundle resource = ResourceBundle.getBundle("xmlPath");
		String path = resource.getString("xmlPaths");
		ModelBean bean = (ModelBean)req.getSession().getAttribute("modelBean");
		ResourceConvert rc = new ResourceConvert();
		
		Document document = DocumentHelper.createDocument();
		
		Element root = document.addElement("xpdl");
		Element packag = root.addElement("Package");
		Element metricmodel = packag.addElement("MetricModel");
		Element id = metricmodel.addElement("Id");
		id.setText(Idm);
		
		System.out.println(id.asXML());
		System.out.println("111"+document.getStringValue());
		
		Element name = metricmodel.addElement("Name");
		name.setText("M-"+ modelname);
		Element metricElement = metricmodel.addElement("MetricElement");
		Element ide = metricElement.addElement("Id");
		ide.setText("00001");
		Element metricObjtype = metricElement.addElement("MetricObjtype");
		metricObjtype.setText(NullToString.nullToString(rc.convert(bean.getProcess())));
		Element metricObj = metricElement.addElement("MetricObj");
		metricObj.setText(NullToString.nullToString(new String((bean.getObject()==null?"":bean.getObject()).getBytes("ISO-8859-1"),"GB2312"))+NullToString.nullToString(new String((bean.getStartobject()==null?"":bean.getStartobject()).getBytes("ISO-8859-1"),"GB2312"))+NullToString.nullToString(new String((bean.getEndobject()==null?"":bean.getEndobject()).getBytes("ISO-8859-1"),"GB2312")));
		Element metricType = metricElement.addElement("MetricType");
		metricType.setText(NullToString.nullToString(rc.convert(bean.getMetric())));
		Element metricName = metricElement.addElement("MetricName");
		Element metricname = metricName.addElement("Name").addText(NullToString.nullToString(rc.convert(bean.getMetricname()))+NullToString.nullToString(rc.convert(bean.getBaseobject()))+NullToString.nullToString(bean.getDeriveobject()));
		Element bmetric = metricName.addElement("D-bmetric");
		bmetric.setText(NullToString.nullToString(bean.getSusable()));
		Element metricDes = metricElement.addElement("MetricDes");
		Element function = metricElement.addElement("Function");
		//function.setText();
		Element predefine = function.addElement("PreDefine");
		predefine.setText(NullToString.nullToString(bean.getFormula()));
		Element defineself = function.addElement("DefineSelf");
		defineself.setText(NullToString.nullToString(bean.getDeffunction()));
		Element frequency = metricElement.addElement("Frequency");
		//frequency.setText(NullToString.nullToString(rc.convert(bean.getFrequencys())));
		Element interval = frequency.addElement("Interval");
		interval.setText(NullToString.nullToString(rc.convert(bean.getFrequency())));
		Element time = frequency.addElement("Time");
		time.setText(NullToString.nullToString(bean.getHour()+"时"+bean.getMinute()+"分"+bean.getSecond()+"秒"));
		Element mmetricname = metricElement.addElement("MmetricName");
		Element mbmetric = mmetricname.addElement("M-bmatric");
		Element mfunction = metricElement.addElement("Mfunction");
		//mfunction.setText(NullToString.nullToString(rc.convert(bean.getMfunction())));
		Element preDefine = mfunction.addElement("PreDfine");
		preDefine.setText(NullToString.nullToString(bean.getMformula()));
		Element DefineSelf = mfunction.addElement("DefineSelf");
		DefineSelf.setText(NullToString.nullToString(bean.getDefineself()));
		Element condition = metricElement.addElement("Condition");
		//condition.setText(NullToString.nullToString(rc.convert(bean.getCondition())));
		Element day = condition.addElement("Day");
		day.setText(NullToString.nullToString(bean.getStartime())+""+NullToString.nullToString(bean.getEndtime()));
		Element times = condition.addElement("Times");
		times.setText(NullToString.nullToString(bean.getDegree()));
		Element treatment = metricElement.addElement("Treatment");
		//treatment.setText(NullToString.nullToString(rc.convert(bean.getTreatment())));
		Element taxis = treatment.addElement("Taxis");
		taxis.setText(NullToString.nullToString(bean.getSerial()));
		Element calculate = treatment.addElement("Calculate");
		calculate.setText(NullToString.nullToString(bean.getCompute()));
		Element display = metricElement.addElement("Display");
		display.setText(NullToString.nullToString(rc.convert(bean.getDisplay())));
		Element scope = metricElement.addElement("Scope");
		scope.setText(NullToString.nullToString(bean.getMaterial())+"到"+NullToString.nullToString(bean.getMaterial2()));
		Element alarm = metricElement.addElement("Alarm");
		alarm.setText(NullToString.nullToString(rc.convert(bean.getAlarm())));
		 XMLWriter output;
	        //输出格式化
	        OutputFormat format = OutputFormat.createPrettyPrint();
	        format.setEncoding("GB2312"); 
	        /*try {
	          //  output = new XMLWriter(new FileOutputStream(path + "\\" + "M-" + bean.getPara() + ".xml"), format);
	            
	          //  System.out.println(document.getPath());
	             output = new XMLWriter( System.out, format );
	            System.out.println("\r\n------------------Start------------------");
	            output.write(document);
	             System.out.println("\r\n-------------------End-------------------");
	           
	            output.close();
	            result = true;
	        } catch (IOException e) {
	            e.printStackTrace();
	        }*/
	        try {
	            output = new XMLWriter(new java.io.FileWriter(path + "\\" + "M-" + modelname + ".xml"), format);
	            output.write(document);
	            output.close();
	            result = true;
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
		return result;
	}
	
	public boolean putInXml(String Id, HttpServletRequest req,String modelname) throws UnsupportedEncodingException, DocumentException {
		boolean result = false;
		ResourceBundle resource = ResourceBundle.getBundle("xmlPath");
		String path = resource.getString("xmlPaths");
		ModelBean bean = (ModelBean)req.getSession().getAttribute("modelBean");
		ResourceConvert rc = new ResourceConvert();
		System.out.println("MMMMMMMMM："+path + "\\" + "M-" + modelname+ ".xml");
		/*SAXReader reader = new SAXReader();
		Document document=null;
		try {
			document = reader.read(path + "\\" + "M-" + modelname+ ".xml");
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		Parserxml pxml = new Parserxml();
		Document document = pxml.getDocument(path+"\\" + "M-" + modelname+ ".xml");
		Element element = pxml.getNode(document,"//xpdl/Package/MetricModel");
		//Node node = document.selectSingleNode("//xpdl/Package/MetricModel");
		//Element metricmodel = (Element)node;
		Element metricElement =element.addElement("MetricElement");
		Element ide = metricElement.addElement("Id");
		ide.setText("0000"+Id);
		Element metricObjtype = metricElement.addElement("MetricObjtype");
		metricObjtype.setText(NullToString.nullToString(rc.convert(bean.getProcess())));
		Element metricObj = metricElement.addElement("MetricObj");
		metricObj.setText(NullToString.nullToString(new String((bean.getObject()==null?"":bean.getObject()).getBytes("ISO-8859-1"),"GB2312"))+NullToString.nullToString(new String((bean.getStartobject()==null?"":bean.getStartobject()).getBytes("ISO-8859-1"),"GB2312"))+NullToString.nullToString(new String((bean.getEndobject()==null?"":bean.getEndobject()).getBytes("ISO-8859-1"),"GB2312")));
		Element metricType = metricElement.addElement("MetricType");
		metricType.setText(NullToString.nullToString(rc.convert(bean.getMetric())));
		Element metricName = metricElement.addElement("MetricName");
		metricName.setText(NullToString.nullToString(rc.convert(bean.getMetricname()))+NullToString.nullToString(rc.convert(bean.getBaseobject()))+NullToString.nullToString(bean.getDeriveobject()));
		Element bmetric = metricName.addElement("D-bmetric");
		bmetric.setText(NullToString.nullToString(bean.getSusable()));
		Element metricDes = metricElement.addElement("MetricDes");
		Element function = metricElement.addElement("Function");
		//function.setText(NullToString.nullToString(rc.convert(bean.getFunction())));
		Element predefine = function.addElement("PreDefine");
		predefine.setText(NullToString.nullToString(bean.getFormula()));
		Element defineself = function.addElement("DefineSelf");
		defineself.setText(NullToString.nullToString(bean.getDeffunction()));
		Element frequency = metricElement.addElement("Frequency");
		//frequency.setText(NullToString.nullToString(rc.convert(bean.getFrequencys())));
		Element interval = frequency.addElement("Interval");
		interval.setText(NullToString.nullToString(rc.convert(bean.getFrequency())));
		Element time = frequency.addElement("Time");
		time.setText(NullToString.nullToString(bean.getHour()+"时"+bean.getMinute()+"分"+bean.getSecond()+"秒"));
		Element mmetricname = metricElement.addElement("MmetricName");
		Element mbmetric = mmetricname.addElement("M-bmatric");
		Element mfunction = metricElement.addElement("Mfunction");
		//mfunction.setText(NullToString.nullToString(rc.convert(bean.getMfunction())));
		Element preDefine = mfunction.addElement("PreDfine");
		preDefine.setText(NullToString.nullToString(bean.getMformula()));
		Element DefineSelf = mfunction.addElement("DefineSelf");
		DefineSelf.setText(NullToString.nullToString(bean.getDefineself()));
		Element condition = metricElement.addElement("Condition");
		//condition.setText(NullToString.nullToString(rc.convert(bean.getCondition())));
		Element day = condition.addElement("Day");
		day.setText(NullToString.nullToString(bean.getStartime())+""+NullToString.nullToString(bean.getEndtime()));
		Element times = condition.addElement("Times");
		times.setText(NullToString.nullToString(bean.getDegree()));
		Element treatment = metricElement.addElement("Treatment");
		//treatment.setText(NullToString.nullToString(rc.convert(bean.getTreatment())));
		Element taxis = treatment.addElement("Taxis");
		taxis.setText(NullToString.nullToString(bean.getSerial()));
		Element calculate = treatment.addElement("Calculate");
		calculate.setText(NullToString.nullToString(bean.getCompute()));
		Element display = metricElement.addElement("Display");
		display.setText(NullToString.nullToString(rc.convert(bean.getDisplay())));
		Element scope = metricElement.addElement("Scope");
		scope.setText(NullToString.nullToString(bean.getMaterial()+"到"+bean.getMaterial2()));
		Element alarm = metricElement.addElement("Alarm");
		alarm.setText(NullToString.nullToString(rc.convert(bean.getAlarm())));
		
		XMLWriter output;
        //输出格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("GB2312"); 
        try {
            output = new XMLWriter(new java.io.FileWriter(path + "\\" + "M-" + modelname + ".xml"), format);
            output.write(document);
            output.close();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*try {
          //  output = new XMLWriter(new FileOutputStream(path + "\\" + "M-" + bean.getPara() + ".xml"), format);
            
          //  System.out.println(document.getPath());
             output = new XMLWriter( System.out, format );
            System.out.println("\r\n------------------Start------------------");
            output.write(document);
             System.out.println("\r\n-------------------End-------------------");
           
            output.close();
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        }*/
	return result;
		
	}
	
	
		
	}

